<?php

namespace Common\Bundle\LibraryBundle\Controller;

use Common\Bundle\LibraryBundle\Entity\Qcm;
use Common\Bundle\LibraryBundle\Entity\Question;
use Common\Bundle\LibraryBundle\Entity\Reponse;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;

use Common\Bundle\LibraryBundle\Form\QcmType;
use Common\Bundle\LibraryBundle\Form\QuestionsType;

/**
 * @Route("/qcm")
 */
class QcmController extends Controller{

    /**
     * @Route("/new/{idTheme}", options={"expose"=true}, defaults={"idQcm"=null})
     * @Route("/{idTheme}/{idQcm}/edit", options={"expose"=true})
     * @Template()
     */
    public function editAction($idTheme, $idQcm)
    {
        $themes = $this->getThemeRepository()->findAllWithParentActif();
        $minQuestion = $this->container->getParameter('min_nb_question');
        $maxQuestion = $this->container->getParameter('max_nb_question');
        $maxReponse = $this->container->getParameter('max_nb_rep');

        if ($idQcm === null) {
            $qcm = new Qcm();
        } else {
            $qcm = $this->getQcmRepository()->find($idQcm);
        }

        if (!$qcm) {
            throw $this->createNotFoundException();
        }

        $em = $this->getDoctrine();

        $form = $this->createForm(new QcmType($idTheme,$em), $qcm);

        if ($this->getRequest()->isMethod("post")) {
            $form->bind($this->getRequest());
            if ($form->isValid()) {
                $qcm->setNom(ucfirst(mb_strtolower($qcm->getNom(), "utf-8")));
                $qcm->setActif(true);
                $qcm->setDateCreation(new \Datetime());
                $qcm->setDateModifcation(new \Datetime());
                $qcm->setUser($this->container->get("security.context")->getToken()->getUser());
                foreach($qcm->getQuestions() as $question)
                {
                    $question->setQcm($qcm);
                    foreach($question->getReponses() as $reponse)
                    {
                        $reponse->setQuestion($question);
                    }
                }
                $this->getDoctrine()->getManager()->persist($qcm);
                $this->getDoctrine()->getManager()->flush();
                if($idQcm)
                {
                    $this->get('session')->getFlashBag()->add('success', 'Qcm modifié');
                }
                else
                {
                    $this->get('session')->getFlashBag()->add('success', 'Qcm ajouté');
                }
                return $this->redirect($this->generateUrl("common_library_theme_index_1",
                    array("idTheme" => $idTheme)));
            }
        }

        return $this->render('CommonLibraryBundle:Qcm:edit.html.twig', array(
            'form' => $form->createView(),
            'idTheme' => $idTheme,
            'idQcm' => $idQcm,
            'themes' => $themes,
            'minQuestion' => $minQuestion,
            'maxQuestion' => $maxQuestion,
            'maxReponse' => $maxReponse
        ));
    }


     /**
     * @Route("/{idQcm}/desactive", options={"expose"=true})
     */
    public function desactiveAction($idQcm)
    {
        $qcm = $this->getQcmRepository()->find($idQcm);
        $themeParent = $qcm->getTheme();

        $em = $this->getDoctrine()->getManager();
        $qcm->setActif(false);
        $em->persist($qcm);
        $em->flush();
        $this->get('session')->getFlashBag()->add('success', 'QCM désactivé');
        if($themeParent != null)
        {
            return $this->redirect($this->generateUrl("common_library_theme_index_1", array("idTheme" => $themeParent->getId())));
        }
        else
        {
            return $this->redirect($this->generateUrl("common_library_theme_index_1", array("idTheme" => 0)));
        }

    }

    /**
     * @Route("/{idQcm}/active", options={"expose"=true})
     */
    public function activeAction($idQcm)
    {
        $qcm = $this->getQcmRepository()->find($idQcm);
        $themeParent = $qcm->getTheme();

        $em = $this->getDoctrine()->getManager();
        $qcm->setActif(true);
        $em->persist($qcm);
        $em->flush();
        $this->get('session')->getFlashBag()->add('success', 'QCM activé');
        if($themeParent != null)
        {
            return $this->redirect($this->generateUrl("common_library_theme_index_1", array("idTheme" => $themeParent->getId())));
        }
        else
        {
            return $this->redirect($this->generateUrl("common_library_theme_index_1", array("idTheme" => 0)));
        }

    }


    /**
     * @Route("/getLesQcms", name="getLesQcms")
     */
    public function getLesQcmsAction()
    {
        $request = $this->getRequest();
        if($request->isXmlHttpRequest()) // pour vérifier la présence d'une requete Ajax
        {
            $idTheme = $request->get('idTheme');
            if(isset($idTheme))
            {
                $qcms = $this->getQcmRepository()->findAllActifWithTheme($idTheme);
            }

            if($qcms == false)
            {
                return new Response(0);
            }
            else
            {
                return new Response(json_encode($qcms, true));
            }
        }
    }

    /**
     * @Route("/getLesQuestions", name="getLesQuestions")
     */
    public function getLesQuestionsAction()
    {
        $request = $this->getRequest();
        if($request->isXmlHttpRequest()) // pour vérifier la présence d'une requete Ajax
        {
            $idQcm = $request->get('idQcm');
            if(isset($idQcm))
            {
                $questions = $this->getQuestionRepository()->findByQcm($idQcm);
            }

            if($questions == false)
            {
                return new Response(0);
            }
            else
            {
                return new Response(json_encode($questions, true));
            }
        }
    }

    /**
     * @return \Common\Bundle\LibraryBundle\Entity\Repository\QcmRepository
     */
    protected function getQcmRepository() {
        return $this->getDoctrine()->getRepository('CommonLibraryBundle:Qcm');
    }

    /**
     * @return \Common\Bundle\LibraryBundle\Entity\Repository\ThemeRepository
     */
    protected function getThemeRepository() {
        return $this->getDoctrine()->getRepository('CommonLibraryBundle:Theme');
    }

    /**
     * @return \Common\Bundle\LibraryBundle\Entity\Repository\TypeQuestionRepository
     */
    protected function getTypeQuestionRepository() {
        return $this->getDoctrine()->getRepository('CommonLibraryBundle:TypeQuestion');
    }

    /**
     * @return \Common\Bundle\LibraryBundle\Entity\Repository\QuestionRepository
     */
    protected function getQuestionRepository() {
        return $this->getDoctrine()->getRepository('CommonLibraryBundle:Question');
    }
} 